package beautysalonsystem.config;

import beautysalonsystem.Util.StpAdminUtil;
import beautysalonsystem.Util.StpCustomerUtil;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaInterceptor(handler -> {

            // 拦截所有接口，排除登录/注册路径
            SaRouter
                    .match("/**")  // 拦截所有请求
                    .notMatch("/user/login/*", "/user/register/*", "/user/logout") // 登录/注册/登出例外
                    .check(r -> {
                        System.out.println("当前 token: " + StpAdminUtil.stp.getTokenValue());
                        // 检查是否登录（任意身份）
                        if (!StpCustomerUtil.stp.isLogin() && !StpAdminUtil.stp.isLogin()) {
                            throw new NotLoginException(null, null, null);
                        }
                    });

        })).addPathPatterns("/**");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("http://localhost:8081")  // 指定前端地址
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true) // 允许携带 cookie
                .maxAge(3600);
    }
}

